package com.company.service;

import com.company.mapper.GoodsMapper;
import com.company.model.Goods;
import com.company.utils.DatabaseUtil;
import com.company.utils.MessageResponse;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class GoodsService {
    public static SqlSession sqlSession = DatabaseUtil.getSession();
    public static GoodsMapper goodsMapper = sqlSession.getMapper(GoodsMapper.class);

    public static List<Goods> findAllGoods() {
        List<Goods> allGoods = goodsMapper.findAll();

        try {
            for(Goods goods: allGoods) {
                goods.loadImage();
            }
            return allGoods;
        } catch (IOException exception) {
            exception.printStackTrace();
            return new ArrayList<>();
        }
    }

    public static List<Goods> findLike(String like) {
        List<Goods> allGoods = goodsMapper.findLike(like);
        try {
            for (Goods goods : allGoods) {
                goods.loadImage();
            }

            return allGoods;
        } catch (IOException exception) {
            exception.printStackTrace();
            return new ArrayList<>();
        }
    }

    public static List<Goods> findByType(String type) {
        List<Goods> allGoods = goodsMapper.findByType(type);
        try {
            for (Goods goods : allGoods) {
                goods.loadImage();
            }

            return allGoods;
        } catch (IOException exception) {
            exception.printStackTrace();
            return new ArrayList<>();
        }
    }

    public static List<Goods> findByNameAndType(String like, String type) {
        List<Goods> allGoods = goodsMapper.findByLikeAndType(like, type);
        try {
            for (Goods goods : allGoods) {
                goods.loadImage();
            }

            return allGoods;
        } catch (IOException exception) {
            exception.printStackTrace();
            return new ArrayList<>();
        }
    }

    public static MessageResponse<Boolean> updateGoods(Goods goods) {
        goodsMapper.updateOne(goods);
        sqlSession.commit();
        return new MessageResponse<>(
                "update success",
                true
        );
    }

    public static MessageResponse<Boolean> insertGoods(Goods goods) {
        goodsMapper.insertOne(goods);
        sqlSession.commit();
        return new MessageResponse<>(
                "insert success",
                true
        );
    }

    public static MessageResponse<Boolean> deleteGoods(int id) {
        goodsMapper.deleteOne(id);
        sqlSession.commit();
        return new MessageResponse<>(
                "delete success",
                true
        );
    }
}
